import numpy as np
import torch


def np_sigmoid(x):
    return 1 / (1 + np.exp(-x))


def np_max(x, axis):
    v_max = np.max(x, axis=axis)
    i_max = np.argmax(x, axis=axis)
    return v_max, i_max


def xywh2xyxy(box):
    if torch.is_tensor(box):
        box_xyxy = torch.zeros_like(box)
    elif isinstance(box, np.ndarray):
        box_xyxy = np.zeros_like(box)
    else:
        raise TypeError("Error data type:", type(box), "unsupported for method xywh2xyxy.")

    box_xyxy[..., 0] = box[..., 0] - box[..., 2] / 2
    box_xyxy[..., 1] = box[..., 1] - box[..., 3] / 2
    box_xyxy[..., 2] = box[..., 0] + box[..., 2] / 2
    box_xyxy[..., 3] = box[..., 1] + box[..., 3] / 2
    return box_xyxy


def xyxy2xywh(box):
    if torch.is_tensor(box):
        box_xywh = torch.zeros_like(box)
    elif isinstance(box, np.ndarray):
        box_xywh = np.zeros_like(box)
    else:
        raise TypeError("Error data type:", type(box), "unsupported for method xyxy2xywh.")

    box_xywh[..., 0] = (box[..., 0] + box[..., 2]) / 2
    box_xywh[..., 1] = (box[..., 1] + box[..., 3]) / 2
    box_xywh[..., 2] = box[..., 2] - box[..., 0]
    box_xywh[..., 3] = box[..., 3] - box[..., 1]
    return box_xywh
